from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from irrigator.models import User
from django.shortcuts import render, redirect
import time

def home(request):
    """
    打开用户列表
    :param request:
    :return:
    """
    userList = User.objects.filter(status=True)
    context = {}
    context['userList'] = userList
    return render(request, 'userList.html', context=context)


def login(request, username, password):
    """
    根据用户名和密码自动登录京东,保存用户昵称到数据库，并跳转到
    :param request:
    :param username: 用户名
    :param password: 密码
    :return: 返回用户列表
    """
    # 打开登录登录页面
    browser = webdriver.Chrome(executable_path='D:/chromedriver.exe')
    browser.get('https://plogin.m.jd.com/user/login.action?appid=375&returnurl=https://z.m.jd.com/user/center.html')
    # 设置用户名和密码并登录
    browser.find_element_by_id('username').send_keys(username)
    browser.find_element_by_id('password').send_keys(password)
    browser.find_element_by_id('loginBtn').click()
    # 打开用户中心页面后获取用户昵称并保存到数据库
    user = User.objects.get(username=username)
    if user.nickname is None:
        try:
            element = WebDriverWait(browser, 10).until(
                EC.presence_of_element_located((By.CLASS_NAME, 'personal-name'))
            )
            nickname = browser.find_elements_by_class_name('personal-name')[0].text
            User.objects.update_or_create({'nickname': nickname}, username=username)
        except Exception:
            pass
    browser.get('https://z.m.jd.com/newIndex.html')
    return redirect('home')

def like(request,username,password):
    """
    登录后自动点赞
    :param request:
    :return:
    """
    browser = webdriver.Chrome(executable_path='D:/chromedriver.exe')
    # browser = webdriver.Firefox(executable_path='D:/browserDriver/geckodriver.exe')
    browser.get('https://plogin.m.jd.com/user/login.action?appid=375&returnurl=https://z.m.jd.com/user/center.html')
    # 设置用户名和密码并登录
    browser.find_element_by_id('username').send_keys(username)
    browser.find_element_by_id('password').send_keys(password)
    browser.find_element_by_id('loginBtn').click()
    # 添加之后，后面点赞操作就不会出现，再次要求登录
    time.sleep(2)
    # 打开文章详情页
    browser.get('https://sq.jr.jd.com/cfContent/report.html?id=973')
    print(browser.session_id)
    # 文章点赞(如果还没点过赞的话)
    try:
        # 判断是否已点赞
        browser.find_elements_by_css_selector("[class='report-zan zan-ed']")
    except Exception:
        browser.find_element_by_id('reportZanWrap').click()

    # 评论点赞
    try:
        element = WebDriverWait(browser, 10).until(
            EC.presence_of_element_located((By.CLASS_NAME, 'comment-item'))
        )
        # elements = browser.find_elements(By.XPATH,'html body.global-event-agent.global-lazy-load div.page-wrap div#comment-wapper div.comment-container div.comment-content div.comment-item div.main-comment div.main-comment-bottom2.clearfix div.main-handle div.main-agree.agree-active span.agree-icon.iconfont.icon-yizan')
        elements = browser.find_elements_by_css_selector("div.main-agree.agree-active > span.agree-icon.iconfont.icon-yizan")
        for ele in elements:
            ele.click()
    except Exception as err:
        print(err)
    browser.get('https://sq.jr.jd.com/cfContent/report.html?id=973')
    return redirect('home')

# 页面浏览量刷新
def refresh(request):
    if request.POST:
        urls = request.POST['urls']
        urls = str(urls).split(',')
        for url in urls:
            count = int(request.POST['count'])
            browser = webdriver.Chrome(executable_path='D:/chromedriver.exe')
            while count > 0:
                browser.get(url)
                count = count - 1
            browser.close()
    return render(request,"viewcount.html")